﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;

namespace myBoard.Framework
{
    public static class Serializer
    {
        public static void Save<T>(string source, T objectToSerialize, string path) where T : class
        {
            try
            {
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                TextWriter tw = new StreamWriter(path);
                serializer.Serialize(tw, objectToSerialize);
                tw.Close();
            }
            catch (Exception ex)
            {
                ExceptionsManager.LogException(source, ex, false);
            }
        }

        public static T Load<T>(string source, string path) where T : class
        {
            try
            {
                if (File.Exists(path))
                {
                    XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
                    StreamReader sr = new StreamReader(path);
                    T deserializedObject = xmlSerializer.Deserialize(sr) as T;
                    sr.Close();
                    return deserializedObject;
                }
                else // If something goes wrong, just return a new instance of the specified type
                {
                    object obj2 = Activator.CreateInstance(typeof(T));
                    return obj2 as T;
                }
            }
            catch (Exception ex) // If something goes wrong, just return a new instance of the specified type
            {
                ExceptionsManager.LogException(source, ex, false);
                object obj2 = Activator.CreateInstance(typeof(T));
                return obj2 as T;
            }
        }
    }
}
